#include "cli_manager.h"
#include "logger.h"
#include <iostream>
#include <string>
#include <signal.h>
#include <csignal>

// 全局CLI管理器指针
CliManager* g_cliManager = nullptr;

// 信号处理函数
void signalHandler(int signal) {
    LOG_INFO("收到信号: " + std::to_string(signal) + "，正在清理资源...");
    if (g_cliManager) {
        delete g_cliManager;
        g_cliManager = nullptr;
    }
    LOG_INFO("程序正常退出");
    exit(signal);
}

// 设置信号处理器
void setupSignalHandlers() {
    LOG_INFO("设置信号处理器");
    signal(SIGINT, signalHandler);  // Ctrl+C
    signal(SIGTERM, signalHandler); // 终止信号
}

// 显示帮助信息
void showHelp(const char* programName) {
    std::cout << "用法: " << programName << " [选项]" << std::endl;
    std::cout << "选项:" << std::endl;
    std::cout << "  --etcd-url <url>  指定ETCD服务器URL (默认: http://127.0.0.1:2379)" << std::endl;
    std::cout << "  --help            显示帮助信息" << std::endl;
    std::cout << "  --log-file <file> 指定日志文件" << std::endl;
    std::cout << "  --debug           启用调试日志级别" << std::endl;
}

int main(int argc, char* argv[]) {
    // 默认ETCD URL
    std::string etcdUrl = "http://127.0.0.1:2379";
    std::string logFile = "";
    
    // 初始化日志系统
#ifdef DEBUG
    Logger::getInstance().setLevel(LogLevel::DEBUG_LEVEL);
    LOG_INFO("Debug模式已启用");
#else
    Logger::getInstance().setLevel(LogLevel::INFO);
#endif

    // 解析命令行参数
    for (int i = 1; i < argc; ++i) {
        std::string arg = argv[i];
        
        if (arg == "--help") {
            showHelp(argv[0]);
            return 0;
        } else if (arg == "--etcd-url" && i + 1 < argc) {
            etcdUrl = argv[++i];
            LOG_INFO("ETCD URL设置为: " + etcdUrl);
        } else if (arg == "--log-file" && i + 1 < argc) {
            logFile = argv[++i];
            Logger::getInstance().setLogToFile(logFile);
            LOG_INFO("日志将输出到文件: " + logFile);
        } else if (arg == "--debug") {
            Logger::getInstance().setLevel(LogLevel::DEBUG_LEVEL);
            LOG_INFO("Debug日志级别已启用");
        }
    }

    try {
        setupSignalHandlers();
        
        LOG_INFO("启动ETCD节点管理器");
        g_cliManager = new CliManager(etcdUrl);
        g_cliManager->run();
        
        delete g_cliManager;
        g_cliManager = nullptr;
        LOG_INFO("程序正常退出");
    } catch (const std::exception& e) {
        LOG_FATAL("程序运行过程中发生异常: " + std::string(e.what()));
        if (g_cliManager) {
            delete g_cliManager;
            g_cliManager = nullptr;
        }
        return 1;
    }

    return 0;
} 